﻿//
//  Monkey Manager
//  Copyright (C) 2012 Victor Tereschenko
//
//  This program is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with this program.  If not, see <http://www.gnu.org/licenses/>.
//     
// ========================================================================

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SQLite;

namespace ManagerDB.SQLiteDB.Queries
{
    class TabController
    {
        SQLiteConnection mConnection;

        public TabController(SQLiteConnection connection)
        {
            mConnection = connection;
        }

        /// <summary>
        /// Gets tag ID by name.
        /// </summary>
        /// <param name="tagName">Name of the tag.</param>
        /// <returns>Tag ID. -1 is returned if the tag with specified name is not found.</returns>
        public long GetTagID(string tagName)
        {
            SQLiteCommand command = new SQLiteCommand("SELECT rowid FROM tags WHERE nameId=@nameId", mConnection);
            command.Parameters.Add(new SQLiteParameter("@nameId", tagName.ToLower()));
            object res = command.ExecuteScalar();
            if (res == null || res == DBNull.Value)
                return -1;

            return (long)res;
        }

        public List<string> GetFileTags(long fileID)
        {
            List<string> tags = new List<string>();
            SQLiteCommand command = new SQLiteCommand("SELECT name FROM tags WHERE rowid in " +
                "(SELECT tagId FROM fileTags WHERE fileId = @fileId)", mConnection);
            command.Parameters.Add(new SQLiteParameter("@fileId", fileID));
            SQLiteDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                string tag = (string)reader["name"];
                tags.Add(tag);
            }
            reader.Close();

            return tags;
        }
    }
}
